package org.tio.sitexxx.web.server.http;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HeaderName;
import org.tio.http.common.HeaderValue;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.common.session.limiter.SessionRateLimiter;
import org.tio.http.common.session.limiter.SessionRateVo;
import org.tio.sitexxx.service.service.conf.IpWhiteListService;
import org.tio.sitexxx.service.vo.AppCode;
import org.tio.utils.SystemTimer;
import org.tio.utils.json.Json;
import org.tio.utils.resp.Resp;

public class TioSiteSessionRateLimiter implements SessionRateLimiter {
	private static Logger log = LoggerFactory.getLogger(TioSiteSessionRateLimiter.class);

	public static final TioSiteSessionRateLimiter me = new TioSiteSessionRateLimiter();

	/**
	 * 相邻两次访问必须间隔的最小时间，单位：毫秒
	 */
	private final Map<String, Integer> map = new HashMap<>();

	/**
	 * 每分钟允许访问的次数
	 */
	private final Map<String, Integer> allowCountMap = new HashMap<>();

	private HttpResponse response;

	private TioSiteSessionRateLimiter() {
		map.put("/logout", 2000);

		map.put("/register/submit", 15000); //注册
		map.put("/register/retrievePwd", 15000); //找回密码步骤一，发邮件
		map.put("/register/setNewPwd", 15000); //找回密码步骤二，设置密码

		map.put("/blog/uploadimg", 3000); //博客上传图片
		map.put("/im/uploadimg", 4000); //im上传单张图片(剪切上传)
		map.put("/im/uploadimgs", 4000);//im上传多张图片

		allowCountMap.put("/login", 12);

		allowCountMap.put("/im/uploadimg", 10);
		allowCountMap.put("/im/uploadimgs", 10);
		allowCountMap.put("/im/uploadvideo", 4);
		allowCountMap.put("/blog/uploadimg", 10);

		response = new HttpResponse();
		try {
			response.setBody(Json.toJson(Resp.fail("小兄Dei，你的手速有点快，单身多少年了？").code(AppCode.ForbidOper.REFUSE)).getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString(), e);
		}
		response.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.TEXT_PLAIN_JSON);

	}

	@Override
	public boolean allow(HttpRequest request, SessionRateVo sessionRateVo) {
		if (IpWhiteListService.isWhiteIp(request.getClientIp())) {
			return true;
		}

		String path = request.getRequestLine().getPath();

		Integer allowCount = allowCountMap.get(path);
		if (allowCount == null) {
			allowCount = 120;
		}
		if (sessionRateVo.getAccessCount().get() > allowCount) {
			return false;
		}

		Integer iv = map.get(path);
		if (iv != null) {
			if (SystemTimer.currTime - sessionRateVo.getLastAccessTime() < iv) {
				return false;
			}
		}

		return true;
	}

	@Override
	public HttpResponse response(HttpRequest request, SessionRateVo sessionRateVo) {
		return response;
		//		return Resps.json(request, Resp.fail("小兄Dei，你的手速有点快，单身多少年了？").code(AppCode.ForbidOper.REFUSE));
	}

}
